

import sys
import typing

from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtWidgets import QMainWindow, QApplication, QWidget, QLabel,QMessageBox
from student_add import Ui_Form
import student_add
from utils_func import log_json
from object_class import Dormitory
import pandas as pd
import change_dorm
import del_dorm
import sqlite3




class Ui_MainWindow_admin(QMainWindow):
    def __init__(self):
        super(Ui_MainWindow_admin, self).__init__()
        self.setWindowFlag(QtCore.Qt.WindowType.MSWindowsFixedSizeDialogHint)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.allocate_dorm)
        self.load_db_to_table()
        self.pushButton_2.clicked.connect(self.change_dorm)
        self.pushButton_3.clicked.connect(self.del_dorm)
        self.action1_3.triggered.connect(self.show_logs)  

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(792, 600)
        MainWindow.setWindowTitle("宿舍分配系统-管理员端")
        MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonStyle.ToolButtonFollowStyle)
        self.centralwidget = QtWidgets.QWidget(parent=MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.widget = QtWidgets.QWidget(parent=self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(20, 0, 751, 61))
        self.widget.setAcceptDrops(False)
        self.widget.setLayoutDirection(QtCore.Qt.LayoutDirection.LeftToRight)
        self.widget.setObjectName("widget")
        self.pushButton = QtWidgets.QPushButton(parent=self.widget)
        self.pushButton.setGeometry(QtCore.QRect(0, 10, 181, 51))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(parent=self.widget)
        self.pushButton_2.setGeometry(QtCore.QRect(200, 10, 171, 51))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(parent=self.widget)
        self.pushButton_3.setGeometry(QtCore.QRect(580, 10, 171, 51))
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_4 = QtWidgets.QPushButton(parent=self.widget)
        self.pushButton_4.setGeometry(QtCore.QRect(390, 10, 181, 51))
        self.pushButton_4.setObjectName("pushButton_4")
        self.tableWidget = QtWidgets.QTableWidget(parent=self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(20, 80, 751, 461))
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(8)
        self.tableWidget.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(5, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(6, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(7, item)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menuBar = QtWidgets.QMenuBar(parent=MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 792, 22))
        self.menuBar.setObjectName("menuBar")
        self.menu = QtWidgets.QMenu(parent=self.menuBar)
        self.menu.setObjectName("menu")
        self.menu_2 = QtWidgets.QMenu(parent=self.menuBar)
        self.menu_2.setObjectName("menu_2")
        self.menu_3 = QtWidgets.QMenu(parent=self.menuBar)
        self.menu_3.setObjectName("menu_3")
        MainWindow.setMenuBar(self.menuBar)
        self.toolBar = QtWidgets.QToolBar(parent=MainWindow)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.ToolBarArea.TopToolBarArea, self.toolBar)
        self.toolBar_2 = QtWidgets.QToolBar(parent=MainWindow)
        self.toolBar_2.setObjectName("toolBar_2")
        MainWindow.addToolBar(QtCore.Qt.ToolBarArea.TopToolBarArea, self.toolBar_2)
        self.toolBar_3 = QtWidgets.QToolBar(parent=MainWindow)
        self.toolBar_3.setObjectName("toolBar_3")
        MainWindow.addToolBar(QtCore.Qt.ToolBarArea.TopToolBarArea, self.toolBar_3)
        self.actionxues1 = QtGui.QAction(parent=MainWindow)
        self.actionxues1.setObjectName("actionxues1")
        self.actiontianjia1 = QtGui.QAction(parent=MainWindow)
        self.actiontianjia1.setObjectName("actiontianjia1")
        self.actionxiugai = QtGui.QAction(parent=MainWindow)
        self.actionxiugai.setObjectName("actionxiugai")
        self.actionshanchu = QtGui.QAction(parent=MainWindow)
        self.actionshanchu.setObjectName("actionshanchu")
        self.action1 = QtGui.QAction(parent=MainWindow)
        self.action1.setObjectName("action1")
        self.action2 = QtGui.QAction(parent=MainWindow)
        self.action2.setObjectName("action2")
        self.actionan = QtGui.QAction(parent=MainWindow)
        self.actionan.setObjectName("actionan")
        self.action1_2 = QtGui.QAction(parent=MainWindow)
        self.action1_2.setObjectName("action1_2")
        self.action1_3 = QtGui.QAction(parent=MainWindow)
        self.action1_3.setObjectName("action1_3")
        self.menu_3.addAction(self.action1_3)
        self.menuBar.addAction(self.menu.menuAction())
        self.menuBar.addAction(self.menu_3.menuAction())
        self.menuBar.addAction(self.menu_2.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        self.pushButton.setText(_translate("MainWindow", "分配宿舍"))
        self.pushButton_2.setText(_translate("MainWindow", "更换宿舍"))
        self.pushButton_3.setText(_translate("MainWindow", "退宿"))
        self.pushButton_4.setText(_translate("MainWindow", "查询"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "姓名"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "学号"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "性别"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("MainWindow", "民族"))
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText(_translate("MainWindow", "班级"))
        item = self.tableWidget.horizontalHeaderItem(5)
        item.setText(_translate("MainWindow", "专业"))
        item = self.tableWidget.horizontalHeaderItem(6)
        item.setText(_translate("MainWindow", "宿舍楼"))
        item = self.tableWidget.horizontalHeaderItem(7)
        item.setText(_translate("MainWindow", "房间号"))
        self.menu.setTitle(_translate("MainWindow", "文件"))
        self.menu_2.setTitle(_translate("MainWindow", "关于"))
        self.menu_3.setTitle(_translate("MainWindow", "日志"))
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
        self.toolBar_2.setWindowTitle(_translate("MainWindow", "toolBar_2"))
        self.toolBar_3.setWindowTitle(_translate("MainWindow", "toolBar_3"))
        self.actionxues1.setText(_translate("MainWindow", "xues1"))
        self.actiontianjia1.setText(_translate("MainWindow", "添加学生"))
        self.actionxiugai.setText(_translate("MainWindow", "修改学生信息"))
        self.actionshanchu.setText(_translate("MainWindow", "删除学生信息"))
        self.action1.setText(_translate("MainWindow", "安全退出"))
        self.action2.setText(_translate("MainWindow", "关于作者"))
        self.actionan.setText(_translate("MainWindow", "安全退出"))
        self.action1_2.setText(_translate("MainWindow", "关于作者"))
        self.action1_3.setText(_translate("MainWindow", "日志查询"))

    
    def allocate_dorm(self):
        try:
            # 连接数据库
            conn = sqlite3.connect('student_management.db')
            cursor = conn.cursor()

            # 获取未分配宿舍的学生
            cursor.execute("SELECT * FROM student_info WHERE dorm_building IS NULL OR dorm_num IS NULL")
            unassigned_students = cursor.fetchall()

            # 初始化宿舍
            male_dorm = Dormitory("男1号楼", 4, 150, "男")
            female_dorm = Dormitory("女1号楼", 4, 150, "女")
            
            male_dorm.male_dorm = male_dorm
            male_dorm.female_dorm = female_dorm
            female_dorm.male_dorm = male_dorm
            female_dorm.female_dorm = female_dorm

            # 分配宿舍
            for student in unassigned_students:
                student_id = student[2]  # 学号在第三列
                gender = student[3]     # 性别在第四列

                if gender == '男':
                    dorm = male_dorm
                elif gender == '女':
                    dorm = female_dorm
                else:
                    continue

                # 分配宿舍
                allocated = False
                for room_num, occupants in dorm.rooms.items():
                    if len(occupants) < dorm.capacity:
                        # 更新数据库
                        cursor.execute("""
                            UPDATE student_info 
                            SET dorm_building = ?, dorm_num = ?
                            WHERE student_id = ?
                        """, (dorm.name, room_num, student_id))
                        dorm.rooms[room_num].append(student_id)
                        allocated = True
                        break

                if not allocated:
                    QMessageBox.warning(self, "警告", f"无法为学号 {student_id} 的学生分配宿舍（{gender}宿舍已满）")

            # 提交更改并关闭连接
            conn.commit()
            conn.close()
            
            log_db.log("管理员端","2000","分配宿舍","所有学生")
            QMessageBox.about(None, '系统提示', '宿舍分配成功')
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"宿舍分配出错: {str(e)}")

    def change_dorm(self):
        self.m=change_dorm.Ui_Form()
        self.m.show()
    def del_dorm(self):
        self.m=del_dorm.Ui_Form()
        self.m.show()
        
    
   
    def load_db_to_table(self):
        try:
            # 连接数据库
            conn = sqlite3.connect('student_management.db')
            df = pd.read_sql_query("SELECT * FROM student_info", conn)
            conn.close()
    
            self.tableWidget.setRowCount(len(df))
            self.tableWidget.setColumnCount(len(df.columns))
    
            self.tableWidget.setHorizontalHeaderLabels(df.columns)
    
            for row in range(len(df)):
                for col in range(len(df.columns)):
                    item = QtWidgets.QTableWidgetItem(str(df.iloc[row, col]))
                    self.tableWidget.setItem(row, col, item)
    
        except Exception as e:
            print(f"加载数据库出错: {str(e)}")
            QtWidgets.QMessageBox.critical(self, "错误", f"无法加载数据库:\n{str(e)}")
    
    def show_logs(self):
        try:
            # 连接数据库
            conn = sqlite3.connect('student_management.db')
            df = pd.read_sql_query("SELECT * FROM operation_log", conn)
            conn.close()

            # 清空表格并设置列数
            self.tableWidget.clear()
            self.tableWidget.setRowCount(len(df))
            self.tableWidget.setColumnCount(len(df.columns))

            # 设置表头
            self.tableWidget.setHorizontalHeaderLabels(df.columns)

            # 填充数据
            for row in range(len(df)):
                for col in range(len(df.columns)):
                    item = QtWidgets.QTableWidgetItem(str(df.iloc[row, col]))
                    self.tableWidget.setItem(row, col, item)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"日志查询出错: {str(e)}")
            
        
    


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = Ui_MainWindow_admin()
    ui.show()

    sys.exit(app.exec())